// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
/**
 * 挂载到想要效果的节点
 */
cc.Class({
    extends: cc.Component,

    properties: {
        /**
        * 飞的金币预制
        */
        coinpre: cc.Prefab,
        /**
        * 目标节点
        */
        coinNode: cc.Node,
        /**
        * 生成金币个数
        */
        createcoin: 20,
        /**
        * 随机范围(random1~random2之间)
        */
        random1: -50,
        random2:  50,
        
        /**
        * 生成到赋予位置的时间
        */
        createTime:  0.15,
        /**
        * 停留时间
        */
         standingTime:  0.2,
        /**
        * 金币移动速度
        */
         coinSpeed:  5000
    },
    onPlayCoinAni(startnode) {
        let tempPlayer = this.moveN1toN2(startnode,this.coinNode)
        for (let i = 0; i < this.createcoin; i++) {
            let pre = cc.instantiate(this.coinpre)
            pre.parent = this.coinNode
            pre.setPosition(tempPlayer)
            let rannumx = Math.floor(Math.random() * (this.random2 - this.random1 + 1) + this.random1)
            let rannumy = Math.floor(Math.random() * (this.random2 - this.random1 + 1) + this.random1)
            pre.runAction(cc.moveBy(this.createTime, rannumx, rannumy))
            this.scheduleOnce(() => {
                pre.stopAllActions()
                let finshend = cc.callFunc(function () {
                    pre.destroy()
                    //this.coinNode.getComponent(cc.Animation).play()
                    // if (i == this.createcoin - 1) {
                    //     //结束
                    //     // this.scheduleOnce(() => {
                    //     //     callback()
                    //     // }, 0.5)
                    // }
                }, this);
                let pos = pre.getPosition()
                let coinpos = cc.v2(0,0)
                let playTime = pos.sub(coinpos).mag() / this.coinSpeed
                pre.runAction(cc.sequence(cc.jumpTo(playTime, coinpos.x, coinpos.y,400,1), finshend))
            }, this.standingTime + this.createTime);

        }
    },
    moveN1toN2(node1, node2) {
        let node1parentworld = node1.convertToWorldSpaceAR(cc.v2(0,0));
        let node1innode2 = node2.convertToNodeSpaceAR(node1parentworld);
        return node1innode2;
        // return node1.parent.convertToNodeSpaceAR(node2.parent.convertToWorldSpaceAR(node2.position))
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {

    },

    // update (dt) {},
});
